package com.qiche.util.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiche.redis.RedisService;
import com.qiche.util.FastDFSUtils;
import com.qiche.util.HttpUtils;
import com.qiche.util.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * PicDownload : 下载上传到微信服务器端的图片到本地
 *
 * @author zhangds
 * @since 2017-04-19 15:06
 */
@Component
public class PicDownload {
    @Resource
    private Token token;
    @Autowired
    private RedisService redisService;
    /**
     * 根据文件id下载文件
     *
     * @param mediaId 媒体id
     * @throws Exception
     */

    public InputStream getInputStream(String mediaId) {
        InputStream is = null;
        String accessToken = token.get_access_token();
        String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
                + accessToken + "&media_id=" + mediaId;
        System.out.println("url:::="+url);
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet
                    .openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            String responseMessage = http.getResponseMessage();

            // 获取文件转化为byte流
            is = http.getInputStream();
            if (is.available()<=115){

                String s = HttpUtils.sendGet(url);
                JSONObject jsonObject = JSON.parseObject(s);
                String errcode = jsonObject.getString("errcode");
                if (errcode!=null){
                    redisService.remove("access_token");
                   // redisManager.delString("access_token");
                    //RedisCache.delString("access_token");
                    return getInputStream(mediaId);
                }
            }
            System.out.println("getInputStream::::is.available()====="+is.available());
            return is;
        } catch (Exception e) {
            System.out.println("--------微信拉去文件失败-----");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取下载图片信息（jpg）
     *
     * @param mediaId 文件的id
     * @throws Exception
     */

    public String saveImageToDisk(String mediaId, String picName, String picPath)
            throws Exception {
        InputStream inputStream = getInputStream( mediaId);
        FastDFSUtils fastDFSUtils = new FastDFSUtils();
        String[] paths = fastDFSUtils.uploadFileByStream(inputStream, picName+".jpg", inputStream.available());
        return "/"+paths[0]+"/"+paths[1];
     /*   FileUtils.copyInputStreamToFile(inputStream
                ,new File(picPath + picName + PropertiesUtils.getPropertiesValueAsString("sys.picture.type")));*/
        /*byte[] data = new byte[10240];
        int len = 0;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(picPath + picName + PropertiesUtils.getPropertiesValueAsString("sys.picture.type"));
            while ((len = inputStream.read(data)) != -1) {
                fileOutputStream.write(data, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }*/
    }

    public static void main(String[] args) throws Exception {
        URL urlGet = new URL("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=7_HBjWJddc5Cactw8vYkcyulnjAx9rIvMZMg249NO3R8WZvTdKmkJZrjR5be6AdYjcP6YCE9aJxaZjDXwgZ4AKVmR1ObfYfl0Tb0n3FdYFv___0PdBefPheRfZJ37sogBb8kOgopepXwEUURDFEKKbAIAJPP&media_id=0689211a62ca8488b19cf30dedf9059089477c004924026bf7e1095f49a21b80");
//        new PicDownload().saveImageToDisk(mediaId, picName, "d:/");
    }
}
